package org.niugang.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.List;

/**
 *  用户信息工具类
 * Copyright: Copyright (c) 2018 863263957@qq.com
 * 
 * @ClassName: UserUtils.java
 * @version: v1.0.0
 * @author: niugang
 * @date: 2018年11月20日 下午12:08:42
 */
public class UserUtils {
   
	/**
	 * Header中 key <----------------------------> value
	 *         Authorization                   {token}
	 */
	private static final String AUTHORIZATION = "Authorization";

	/**
	 * 获取当前请求的token
	 * @return
	 */
	public static String getCurrentToken() {
		return HttpUtils.getHeaders(HttpUtils.getHttpServletRequest()).get(AUTHORIZATION);
	}

	/**
	 * 获取当前请求的用户Id
	 * @return
	 */
	public static String getCurrentPrinciple() {
		return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}

	/**
	 * 判读当前token用户是否为接口所需的参数username
	 *
	 * @param username
	 * @return
	 */
	public static boolean isMyself(String username) {
		return username.equals(getCurrentPrinciple());
	}

	/**
	 * 获取当前请求Authentication
	 *
	 * @return
	 */
	public static Authentication getCurrentAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	/**
	 * 获取当前请求的权限信息
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<SimpleGrantedAuthority> getCurrentAuthorities() {
		return (List<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
	}

	/**
	 * @param role
	 * @return
	 */
	public static boolean hasRole(String role) {
		if (!role.startsWith("ROLE_")) {
			role = "ROLE_" + role;
		}
		boolean hasRole = false;
		List<SimpleGrantedAuthority> list = getCurrentAuthorities();
		for (SimpleGrantedAuthority s : list) {
			if (role.equals(s.getAuthority())) {
				hasRole = true;
				break;
			}
		}
		return hasRole;
	}

}
